<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="单据编号" prop="documentCode">
        <el-input
          v-model="queryParams.documentCode"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据名称" prop="documentName">
        <el-input
          v-model="queryParams.documentName"
          placeholder="请输入单据名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归还日期" prop="params">
        <el-date-picker
          clearable
          v-model="queryParams.params"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          placeholder="请选择归还日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>

    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tm:return:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="returnList" @selection-change="handleSelectionChange">
      <el-table-column label="单据编号" align="center" prop="documentCode">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['tm:return:query']"
          >{{ scope.row.documentCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="单据名称" align="center" prop="documentName" />
      <el-table-column label="归还日期" align="center" prop="documentDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.documentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归还人" align="center" prop="returnName" />
      <el-table-column label="部门" align="center" prop="returnDeptName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="180">
        <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-video-play"
              v-if="scope.row.status =='PREPARE'"
              @click="handleExecute(scope.row)"
              v-hasPermi="['tm:return:execute']"
            >执行入库</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.status =='PREPARE'"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['tm:return:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="scope.row.status =='PREPARE' || scope.row.status =='CONFIRMED'"
              @click="handleDelete(scope.row)"
              v-hasPermi="['tm:return:remove']"
            >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>

    <!-- 添加或修改归还对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编号" prop="documentCode">
              <el-input v-model="form.documentCode" placeholder="请输入单据编号"/>
            </el-form-item>
          </el-col>
<!--          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                         active-color="#13ce66"
                         active-text="自动生成"
                         @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view' && form.status =='PREPARE'">
              </el-switch>
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="单据名称" prop="documentName">
              <el-input v-model="form.documentName" placeholder="请输入单据名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库日期" prop="documentDate">
              <el-date-picker clearable
                              v-model="form.documentDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择出库日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归还人" prop="returnName">
              <el-input v-model="form.returnName"  placeholder="请选择归还人">
                <el-button
                  slot="append"
                  @click="handleUserSelect"
                  icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="returnDeptName">
              <el-input v-model="form.returnDeptName" :disabled="true" placeholder="请选择部门"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请填写归还原因"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider v-if="form.documentId !=null" content-position="center">明细信息</el-divider>
      <el-card shadow="always" v-if="form.documentId !=null" class="box-card">
        <Returnline ref="line"
                    :documentId="form.documentId"
                    :returnId="form.returnId"
                    :returnName="form.returnName"
                    :optType="optType">
        </Returnline>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE' ">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' && optType !='view' ">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <UserSingleSelect ref="userSelect" @onSelected="onUserSelected"></UserSingleSelect>
  </div>
</template>

<script>
import { listReturn, getReturn, delReturn, addReturn, updateReturn, execute } from "@/api/mes/tm/return";
import Returnline from "@/views/mes/tm/return/line";
import { genCode } from "@/api/system/autocode/rule";
import UserSingleSelect from "@/components/userSelect/single.vue"

export default {
  name: "Return",
  components: {UserSingleSelect,Returnline},
  dicts: ['mes_order_status'],
  data() {
    return {
      autoGenFlag: false,
      optType: undefined,
      returnName:null,
      returnDeptName: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 归还表格数据
      returnList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentCode: null,
        documentName: null,
        params: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        documentDate: [
          {required: true, message: "入库日期不能为空", trigger: "blur"}
        ],
        returnName: [
          {required: true, message: "归还人不能为空", trigger: "blur"}
        ],
        returnDeptName: [
          {required: true, message: "部门不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询归还列表 */
    getList() {
      this.loading = true;
      const query = { ...this.queryParams };
      if (query.params && query.params.length === 2) {
        query.params = {
          beginTime: query.params[0],
          endTime: query.params[1]
        };
      } else {
        query.params = null;
      }
      listReturn(query).then(response => {
        console.log(response);
        this.returnList = response.rows;
        this.returnName = response.nickName;
        this.returnDeptName= response.deptName;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        documentId: null,
        documentCode: null,
        documentName: null,
        documentDate: new Date(),
        returnId: null,
        returnCode: null,
        returnName: this.returnName,
        returnDeptId: null,
        returnDeptCode: null,
        returnDeptName: this.returnDeptName,
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tenantId: null
      };
      this.autoGenFlag = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.documentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('DOCUMENT_RETURN_CODE').then(response => {
        this.form.documentCode = response;
      });
      this.open = true;
      this.title = "添加工器具归还";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const documentId = row.documentId || this.ids
      getReturn(documentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改归还";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.documentId != null) {
            updateReturn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReturn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const documentIds = row.documentId || this.ids;
      this.$modal.confirm('是否确认删除工器具归还编号为"' + documentIds + '"的数据项？').then(function() {
        return delReturn(documentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tm/return/export', {
        ...this.queryParams
      }, `return_${new Date().getTime()}.xlsx`)
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      getReturn(row.documentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看工器具归还单据信息";
        this.optType = "view";
      });
    },
    //执行归还
    handleExecute(row) {
      const documentIds = row.documentId || this.ids;
      this.$modal.confirm('确认执行归还？').then(function () {
        return execute(documentIds)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("归还成功");
      }).catch(() => {
      });
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('DOCUMENT_RETURN_CODE').then(response => {
          this.form.documentCode = response;
        });
      } else {
        this.form.documentCode = null;
      }
    },
    //点击人员选择按钮
    handleUserSelect() {
      this.$refs.userSelect.showFlag = true;
    },
    //人员选择返回
    onUserSelected(row) {
      this.form.returnName = row.nickName;
      this.form.returnId = row.userId;
      this.form.returnCode = row.userName;
      this.form.returnDeptId = row.deptId
      this.form.returnDeptName = row.dept.deptName
      this.$forceUpdate()
    }
  }
};
</script>
